#include "clientwidget.h"
#include "ui_clientwidget.h"

clientwidget::clientwidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::clientwidget)
{
    ui->setupUi(this);
    tcpSocket = nullptr;
    setWindowTitle("客户端");

    tcpSocket = new QTcpSocket(this);
    connect(tcpSocket,&QTcpSocket::connected,[=](){
        ui->textBrowserRead->setText("服务器连接成功！");
    });

    connect(tcpSocket,&QTcpSocket::readyRead,[=](){
        //获取通信套接字的内容
        QString str = tcpSocket->readAll();
        //在显示编辑区域显示
        ui->textBrowserRead->append("服务端："+ str);
    });
}

clientwidget::~clientwidget()
{
    delete ui;
}

void clientwidget::on_Buttonconnect_clicked()
{

    //获取ip地址和端口号
    QString ip = ui->lineEditIP->text();
    quint16 port = ui->lineEditPort->text().toUInt();
    qDebug()<<ip<<port;

    //与服务器连接
    tcpSocket->connectToHost(ip,port);
    if(tcpSocket->waitForConnected(3000)){
        qDebug()<<"状态：已连接";
    }else{
        qDebug()<<"状态：连接失败";
    }

}


void clientwidget::on_Buttonsend_clicked()
{
    if(nullptr==tcpSocket) //连接失败则不发送
        return;

    //获取发送的信息
    QString str = ui->textEditWrite->toPlainText();

    //将信息写入到通信套接字
    tcpSocket->write(str.toUtf8().data());

    //将自己的信息显示在聊天窗口
    ui->textBrowserRead->append("客户端："+str);

}

void clientwidget::on_Buttonclose_clicked()
{
    if(nullptr == tcpSocket)
        return;
    tcpSocket->disconnectFromHost(); //断开与服务器的连接
    tcpSocket->close(); //关闭通信套接字
}
